<template>
  <div>
    <el-tabs
      type="card"
      closable
      v-model="currentTab.name"
      class="demo-tabs"
      @tab-click="handleClick"
      @tab-remove="remove"
    >
      <el-tab-pane
        v-for="tab in tabs"
        :key="tab.name"
        :label="tab.name"
        :name="tab.name"
      >
        <template #label>
          <span class="custom-tabs-label">
            <el-icon>
              <component :is="tab.icon"> </component>
            </el-icon>
            <span>&nbsp;{{ tab.name }}</span>
          </span>
        </template>
      </el-tab-pane>
    </el-tabs>
    <RouterView />
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import { useTabsStore } from "@/store/tabs";
import { storeToRefs } from "pinia";
import { useUserStore } from "@/store/auth";
const router = useRouter();
const route = useRoute();
const tabsStore = useTabsStore();

const { tabs, currentTab } = storeToRefs(tabsStore);
const { addTab, setCurrentTab, removeTab } = tabsStore;

//点击标签
const handleClick = ({ index }: { index: number }) => {
  setCurrentTab(tabs.value[index].name, tabs.value[index].url); //设置当前高亮
  router.push(tabs.value[index].url); //跳转
};
//删除标签
const remove = (TabPaneName: string) => {
  removeTab(TabPaneName);
  router.push(currentTab.value.url);
};
//
const userStore = useUserStore();
const { menu } = storeToRefs(userStore);
//初始页面顶部标签显示 刷新显示
const findObjectByUrl = (arr: any, url: string) => {
  for (const item of arr) {
    if (item.url === url) {
      return item;
    }
    if (item.children) {
      const found: any = findObjectByUrl(item.children, url);
      if (found) {
        return found;
      }
    }
  }
  return null;
};
const { name, url, icon } = findObjectByUrl(menu.value, route.path);
addTab(name, url, icon);
setCurrentTab(name, url);
</script>

<style lang="less" scoped>
.demo-tabs {
  :deep(.is-active) {
    background-color: rgb(34, 136, 255) !important;
    color: #fff !important;
  }
}
</style>
